"use client";

import { useEffect, useState } from 'react';
import grainImage from '@/assets/images/grain.jpg';
import { getHomeData } from '@/lib/api';
import type { HomeData } from '@/lib/api';
import { motion } from 'framer-motion';

export const ContactSection = () => {
  const [homeData, setHomeData] = useState<HomeData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchData = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const data = await getHomeData();
      console.log('Fetched home data:', data);
      // 更宽松的数据验证，如果contact_links不存在或格式不正确，则使用空数组
      if (!data) {
        throw new Error('获取首页数据失败');
      }
      // 确保contact_links.links是一个数组，如果不是则初始化为空数组
      if (!data.contact_links) {
        data.contact_links = { links: [] };
      } else if (!data.contact_links.links) {
        data.contact_links.links = [];
      } else if (!Array.isArray(data.contact_links.links)) {
        data.contact_links.links = [];
      }
      setHomeData(data);
    } catch (error) {
      console.error('Error fetching home data:', error);
      // 提供更具体的错误信息
      const err = error instanceof Error ? error : new Error(String(error));
      let errorMessage = '加载联系方式失败，请稍后重试';
      
      if (err.message.includes('Failed to fetch') || err.message.includes('网络连接失败')) {
        errorMessage = '网络连接失败，请检查网络连接后重试';
      } else if (err.message.includes('API基础URL未配置')) {
        errorMessage = '系统配置错误，请联系管理员';
      } else if (err.message.includes('请求超时')) {
        errorMessage = '服务器响应超时，请稍后重试';
      }
      
      setError(errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);
  
  // 添加重试功能
  const retryFetch = () => {
    setIsLoading(true);
    setError(null);
    fetchData();
  };

  if (isLoading) {
    return (
      <section id="contact" className='py-16 pt-12 lg:py-24 lg:pt-20'>
        <div className='container'>
          <motion.div 
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className='text-center flex justify-center items-center p-8'
          >
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-300"></div>
          </motion.div>
        </div>
      </section>
    );
  }

  if (error) {
    return (
      <section id="contact" className='py-16 pt-12 lg:py-24 lg:pt-20'>
        <div className='container'>
          <motion.div 
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className='flex flex-col items-center justify-center gap-4 text-center p-8 bg-red-400/5 rounded-2xl'
          >
            <div className='p-4 bg-red-400/10 rounded-xl border border-red-400/20 animate-pulse'>
              <span className='text-2xl'>⚠️</span>
            </div>
            <div className='text-red-400 font-medium'>{error}</div>
            <motion.button 
              onClick={retryFetch}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              className='mt-2 px-4 py-2 bg-red-400/20 text-red-300 rounded-lg hover:bg-red-400/30 transition-colors flex items-center gap-2'
            >
              <span>重试加载</span>
              <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
            </motion.button>
          </motion.div>
        </div>
      </section>
    );
  }

  return (
    <section id="contact" className='py-16 pt-12 lg:py-24 lg:pt-20'>
      <div className='container'>
        <motion.div 
          initial={{ opacity: 0, y: 30 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, margin: "-10% 0px" }}
          transition={{ duration: 0.6, ease: [0.1, 0.3, 0.2, 1] }}
          className='bg-gradient-to-r from-emerald-300 to-sky-400 text-indigo-950 py-10 md:gap-16 px-10 rounded-3xl text-center md:text-left relative overflow-hidden z-0 shadow-lg shadow-emerald-300/10 hover:shadow-emerald-300/20 transition-shadow duration-500'
        >
          <div className='absolute inset-0 opacity-5 -z-10' style={{
            backgroundImage: `url(${grainImage.src})`
          }}></div>
          <div className='absolute inset-0 bg-gradient-to-tr from-transparent via-white/5 to-white/10 -z-10'></div>
          <div className='flex flex-col md:flex-row gap-8 items-center'>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              whileInView={{ opacity: 1, x: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.4, delay: 0.2 }}
            >
              <h2 className='font-serif text-2xl md:text-3xl lg:text-4xl'>
                {homeData?.contact}
              </h2>
              <p className='text-sm md:text-base mt-2 text-indigo-950/80 max-w-md'>
                {homeData?.contact_description}
              </p>
            </motion.div>
            <div className='flex flex-wrap gap-4 justify-center md:justify-start'>
              {Array.isArray(homeData?.contact_links?.links) && homeData.contact_links.links.map((link, index) => (
                <motion.a
                  key={index}
                  href={link.url}
                  target='_blank'
                  initial={{ opacity: 0, y: 20 }}
                  whileInView={{ opacity: 1, y: 0 }}
                  viewport={{ once: true }}
                  transition={{ duration: 0.4, delay: 0.2 + index * 0.1 }}
                  whileHover={{ 
                    scale: 1.05,
                    boxShadow: '0 10px 25px -5px rgba(16, 185, 129, 0.2)' 
                  }}
                  whileTap={{ scale: 0.98 }}
                  className='bg-gradient-to-r from-emerald-300/10 to-sky-400/10 rounded-2xl inline-flex items-center px-8 h-12 gap-2 border border-emerald-300/30 backdrop-blur-sm'
                >
                  <span className='font-semibold text-indigo-950/80'>{link.name}</span>
                </motion.a>
              ))}
            </div>
          </div>
        </motion.div>
      </div>
    </section>
  );
};
